const AIAssistant = require('../models/AIAssistant');
const { catchAsync } = require('../utils/errorHandler');
const dotenv = require('dotenv');

dotenv.config();

// 初始化用户的AI助手
exports.initializeAssistant = catchAsync(async (req, res) => {
  // 检查用户是否已有AI助手
  let assistant = await AIAssistant.findOne({ user: req.user.id });

  if (assistant) {
    return res.status(400).json({
      success: false,
      message: '用户已有AI助手',
    });
  }

  // 创建新的AI助手
  assistant = await AIAssistant.create({
    user: req.user.id,
    name: req.body.name || '豆包',
    avatar: req.body.avatar || 'default-assistant-avatar.png',
    personality: req.body.personality || '友好',
  });

  res.status(201).json({
    success: true,
    message: 'AI助手初始化成功',
    data: { assistant },
  });
});

// 获取用户的AI助手信息
exports.getAssistant = catchAsync(async (req, res) => {
  const assistant = await AIAssistant.findOne({ user: req.user.id });

  if (!assistant) {
    return res.status(404).json({
      success: false,
      message: '未找到AI助手',
    });
  }

  res.status(200).json({
    success: true,
    data: { assistant },
  });
});

// 更新AI助手设置
exports.updateAssistant = catchAsync(async (req, res) => {
  const { name, avatar, personality, specialties, preferences } = req.body;

  // 查找并更新AI助手
  const assistant = await AIAssistant.findOneAndUpdate(
    { user: req.user.id },
    {
      name,
      avatar,
      personality,
      specialties,
      preferences,
    },
    {
      new: true,
      runValidators: true,
    }
  );

  if (!assistant) {
    return res.status(404).json({
      success: false,
      message: '未找到AI助手',
    });
  }

  res.status(200).json({
    success: true,
    message: 'AI助手设置更新成功',
    data: { assistant },
  });
});

// 与AI助手交互
exports.interactWithAssistant = catchAsync(async (req, res) => {
  const { query, projectId, codeSnippet, learningGoal } = req.body;

  // 查找用户的AI助手
  const assistant = await AIAssistant.findOne({ user: req.user.id });

  if (!assistant) {
    return res.status(404).json({
      success: false,
      message: '未找到AI助手',
    });
  }

  try {
    // 调用AI API获取响应
    // 这里是模拟的AI响应，实际项目中需要调用真实的AI API
    const aiResponse = await mockAIResponse(query, assistant.personality, {
      projectId,
      codeSnippet,
      learningGoal,
    });

    // 记录交互
    assistant.interactions.push({
      timestamp: Date.now(),
      userQuery: query,
      assistantResponse: aiResponse,
      context: {
        projectId,
        codeSnippet,
        learningGoal,
      },
    });

    // 更新使用统计
    assistant.usageStats.totalInteractions += 1;
    assistant.usageStats.lastInteractionDate = Date.now();

    await assistant.save();

    res.status(200).json({
      success: true,
      data: {
        response: aiResponse,
        assistant: {
          name: assistant.name,
          avatar: assistant.avatar,
          personality: assistant.personality,
        },
      },
    });
  } catch (error) {
    console.error('AI交互错误:', error);
    res.status(500).json({
      success: false,
      message: 'AI助手交互失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined,
    });
  }
});

// 提供AI助手交互的反馈
exports.provideAssistantFeedback = catchAsync(async (req, res) => {
  const { interactionId, helpful, rating, comment } = req.body;

  // 查找用户的AI助手
  const assistant = await AIAssistant.findOne({ user: req.user.id });

  if (!assistant) {
    return res.status(404).json({
      success: false,
      message: '未找到AI助手',
    });
  }

  // 查找交互
  const interaction = assistant.interactions.id(interactionId);

  if (!interaction) {
    return res.status(404).json({
      success: false,
      message: '未找到交互记录',
    });
  }

  // 更新反馈
  interaction.feedback = {
    helpful,
    rating,
    comment,
  };

  // 更新统计数据
  if (helpful) {
    assistant.usageStats.helpfulResponses += 1;
  }

  // 计算平均评分
  const ratedInteractions = assistant.interactions.filter(
    (i) => i.feedback && i.feedback.rating
  );
  const totalRating = ratedInteractions.reduce(
    (sum, i) => sum + i.feedback.rating,
    0
  );
  assistant.usageStats.averageRating =
    ratedInteractions.length > 0 ? totalRating / ratedInteractions.length : 0;

  await assistant.save();

  res.status(200).json({
    success: true,
    message: 'AI助手反馈提交成功',
    data: {
      feedback: interaction.feedback,
      stats: assistant.usageStats,
    },
  });
});

// 获取AI助手交互历史
exports.getInteractionHistory = catchAsync(async (req, res) => {
  // 分页参数
  const page = parseInt(req.query.page, 10) || 1;
  const limit = parseInt(req.query.limit, 10) || 10;
  const skip = (page - 1) * limit;

  // 查找用户的AI助手
  const assistant = await AIAssistant.findOne({ user: req.user.id });

  if (!assistant) {
    return res.status(404).json({
      success: false,
      message: '未找到AI助手',
    });
  }

  // 获取交互历史
  const interactions = assistant.interactions
    .sort((a, b) => b.timestamp - a.timestamp) // 按时间降序排序
    .slice(skip, skip + limit);

  res.status(200).json({
    success: true,
    data: {
      interactions,
      pagination: {
        total: assistant.interactions.length,
        page,
        limit,
        pages: Math.ceil(assistant.interactions.length / limit),
      },
    },
  });
});

// 更新学习档案
exports.updateLearningProfile = catchAsync(async (req, res) => {
  const { strengths, areasToImprove, recommendedConcepts, learningPath } = req.body;

  // 查找并更新AI助手
  const assistant = await AIAssistant.findOneAndUpdate(
    { user: req.user.id },
    {
      'learningProfile.strengths': strengths,
      'learningProfile.areasToImprove': areasToImprove,
      'learningProfile.recommendedConcepts': recommendedConcepts,
      'learningProfile.learningPath': learningPath,
    },
    {
      new: true,
      runValidators: true,
    }
  );

  if (!assistant) {
    return res.status(404).json({
      success: false,
      message: '未找到AI助手',
    });
  }

  res.status(200).json({
    success: true,
    message: '学习档案更新成功',
    data: {
      learningProfile: assistant.learningProfile,
    },
  });
});

// 模拟AI响应（实际项目中需要替换为真实的AI API调用）
const mockAIResponse = async (query, personality, context) => {
  // 模拟API调用延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  // 根据不同的个性生成不同风格的回复
  let response = '';
  
  switch (personality) {
    case '友好':
      response = `嗨！我很乐意帮助你解决这个问题。${generateResponseByQuery(query, context)}`;
      break;
    case '专业':
      response = `根据你的问题，我提供以下专业解答：${generateResponseByQuery(query, context)}`;
      break;
    case '幽默':
      response = `哈哈，有趣的问题！让我想想...${generateResponseByQuery(query, context)}`;
      break;
    case '鼓励':
      response = `你提出了一个很好的问题！继续保持好奇心。${generateResponseByQuery(query, context)}`;
      break;
    case '挑战':
      response = `这是个有挑战性的问题，让我们一起思考更深入。${generateResponseByQuery(query, context)}`;
      break;
    default:
      response = `${generateResponseByQuery(query, context)}`;
  }

  return response;
};

// 根据查询生成响应内容
const generateResponseByQuery = (query, context) => {
  // 这里是简单的模拟逻辑，实际项目中需要更复杂的AI处理
  if (query.includes('循环')) {
    return '循环是编程中的基本概念，它允许你重复执行一段代码。在Scratch中，你可以使用"重复"积木来创建循环。';
  } else if (query.includes('变量')) {
    return '变量就像是一个可以存储信息的容器。在Scratch中，你可以创建变量来记录分数、生命值或其他需要跟踪的数据。';
  } else if (query.includes('条件')) {
    return '条件语句允许你的程序根据不同情况做出不同决定。在Scratch中，你可以使用"如果...那么..."积木来创建条件判断。';
  } else if (query.includes('错误') || query.includes('bug')) {
    return '调试是编程的重要部分。尝试逐步检查你的代码，看看哪里可能出了问题。你也可以添加一些显示变量值的积木来帮助找出问题所在。';
  } else if (query.includes('游戏')) {
    return '创建游戏需要考虑几个关键元素：角色、控制、规则和目标。你可以从简单的躲避游戏开始，然后逐步添加更多功能。';
  } else {
    return '这是一个有趣的问题！我建议你尝试将问题分解成更小的部分，逐步解决。如果你有具体的代码或项目，可以分享给我，我会提供更具体的建议。';
  }
};